package cn.iocoder.yudao.module.promotion.groupon.mq;

import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.api.trade.order.dto.TradeOrderRespDTO;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderTypeEnum;
import cn.iocoder.yudao.module.api.trade.order.message.TradeOrderCreatedMessage;
import cn.iocoder.yudao.module.api.trade.order.message.TradeOrderPaidMessage;
import cn.iocoder.yudao.module.promotion.groupon.pojo.dto.GrouponOrderSubmitDTO;
import cn.iocoder.yudao.module.promotion.groupon.service.app.AppGrouponOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/14
 */
@Component
@Slf4j
public class GrouponOrderConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeOrderCreatedMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        log.info("[promotion/groupon][onMessage][交易订单创建完成({})]", order.getNo());
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            return;
        }
        GrouponOrderSubmitDTO submitDTO = new GrouponOrderSubmitDTO();
        submitDTO.setPackageId(order.getGrouponPackageId());
        submitDTO.setTradeNo(order.getNo());
        submitDTO.setPayNo(order.getPayNo());
        SpringUtil.getBean(AppGrouponOrderService.class).submit(submitDTO, order.getUserId());
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(TradeOrderPaidMessage message) {
        TradeOrderRespDTO order = message.getOrder();
        log.info("[promotion/groupon][onMessage][交易订单付款完成({})]", order.getNo());
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            return;
        }
        SpringUtil.getBean(AppGrouponOrderService.class).checkAndUpdatePaid(order.getNo(), order.getPayNo());
    }

}
